package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	// 打印查询的语句
	orm.Debug, _ = beego.AppConfig.Bool("APP_DEBUG")

	driverName := beego.AppConfig.String("DB_CONNECTION")
	// 注册数据库驱动
	_ = orm.RegisterDriver(driverName, orm.DRMySQL)
	// 数据库连接
	user := beego.AppConfig.String("DB_USERNAME")
	password := beego.AppConfig.String("DB_PASSWORD")
	host := beego.AppConfig.String("DB_HOST")
	port := beego.AppConfig.String("DB_PORT")
	database := beego.AppConfig.String("DB_DATABASE")
	// 设置数据库基本信息
	dataSource := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + database + "?charset=utf8"
	err := orm.RegisterDataBase("default", driverName, dataSource)
	if err != nil {
		logs.Error("连接数据库出错")
		return
	}
	logs.Info("连接数据库成功")

	// 映射model数据 // 需要在init中注册定义的model
	orm.RegisterModel(new(User), new(Article), new(Profile), new(Tag))
	// 生成表
	_ = orm.RunSyncdb("default", false, true)
}
